package com.dmg.sp.controller;


import com.dmg.sp.entity.Menu;
import com.dmg.sp.entity.MyUserDetails;
import com.dmg.sp.entity.Role;
import com.dmg.sp.service.MenuService;
import com.dmg.sp.utils.Result;
import com.dmg.sp.vo.IdVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 获取当前登录人的权限
     * @return
     */
    @PostMapping("/getMyAuth")
    public Result getMyAuth(){
        //从认证信息上下文中 获取用户权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        MyUserDetails myUserDetails =(MyUserDetails) authentication.getPrincipal();
        return Result.success(myUserDetails.getAuthList());
    }

    /**
     * 获取所有菜单和权限(包括按钮)
     * @return
     */
    @PostMapping("/getMenuList")
    public Result getMenuList(){
        //根据用户id 获取对应的菜单
        List<Menu> list=menuService.getMenuList();
        return Result.success(list);
    }

    /**
     * 添加菜单
     * @return
     */
    @PostMapping("/addMenu")
    public Result addMenu(@RequestBody Menu menu){
        menuService.addMenu(menu);
        return Result.success();
    }

    /**
     * 修改菜单
     * @return
     */
    @PostMapping("/editMenu")
    public Result editMenu(@RequestBody Menu menu){
        menuService.editMenu(menu);
        return Result.success();
    }

    /**
     * 删除菜单
     * @return
     */
    @PostMapping("/deleteMenu")
    public Result deleteMenu(@RequestBody Menu menu){
        menuService.deleteMenu(menu.getId());
        return Result.success();
    }

    /**
     * 查看菜单详情
     * @return
     */
    @PostMapping("/getMenuById")
    public Result getMenuById(@RequestBody Menu menu){
        return Result.success(menuService.getMenuById(menu.getId()));
    }

    /**
     * 查看角色对应的权限
     * @return
     */
    @PostMapping("/getRoleAuth")
    public Result getRoleAuth(@RequestBody IdVo vo){
        return Result.success(menuService.getRoleAuth(vo.getRoleId()));
    }
}
